package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmCategorySchema;
import com.ruoyi.jihuo.mapper.JhTmCategorySchemaMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author：LXY
 * @DATE：2025-09-14 12:30
 * @Description：获取产品发布规则
 */
@Component
@Slf4j
public class Jh40GetAddProductSchemaHandler  implements  PriorityHandler {
    @Autowired
    private JhTmCategorySchemaMapper jhTmCategorySchemaMapper;

    @Autowired
    private CallTaoApiService callTaoApiService;
    @Override
    public int getPriority() {
        return 40;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        JSONObject data = request.getData();
        Long cid = data.getLong("categoryId");
        JhTmAccount jhTmAccount = data.getObject("tmAccount", JhTmAccount.class);
        QueryWrapper<JhTmCategorySchema> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("jh_cat_id", cid);
        try {
            JhTmCategorySchema jhTmCategorySchema = jhTmCategorySchemaMapper.selectOne(queryWrapper);
            // 这个判空暂定，后面有可能会直接初始化一些，因为类别是有限的
            if (jhTmCategorySchema == null) {
                String schema = callTaoApiService.getAddProductSchema(jhTmAccount, cid);
                jhTmCategorySchema = new JhTmCategorySchema();
                jhTmCategorySchema.setJhCatSchema(schema);
                jhTmCategorySchema.setJhCatId(cid);
                jhTmCategorySchema.setJhCatLevel(3);
                jhTmCategorySchema.setJhTmAccountId(jhTmAccount.getJhUserId());
                // todo 测试代码，insert 获取不到当前登录用户
                jhTmCategorySchema.setJhCreatedBy(jhTmAccount.getJhAccount());
                jhTmCategorySchema.setJhUpdatedBy(jhTmAccount.getJhAccount());
                jhTmCategorySchemaMapper.insert(jhTmCategorySchema);
            }
            data.put("categorySchema", jhTmCategorySchema.getJhCatSchema());
        }catch (Exception e){
            request.setErrorInfo("获取产品发布规则时发生异常:" + e.getMessage());
            throw new RuntimeException("获取产品发布规则时发生异常:"+e);
        }
        return true;
    }
}
